import React from 'react';
import {deepFullCopy, messages} from 'share/common'
import { Form, Row, Col, Tree, Icon, Menu, Dropdown, Button, message, Spin, Popover } from 'antd'
const TreeNode = Tree.TreeNode;
import NewDocumentTitle from 'containers/setting/help-document-management/new-document-title'
import documentService from 'containers/setting/help-document-management/help-document.service'
import 'styles/setting/help-document-management/help-document-menu.scss'
import { connect } from 'react-redux'

class HelpDocumentMenu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      newTitleVisible: false,
      isSorting: false,
      sourceData: [],
      data: [],
      selectedTreeNode: this.props.selectedId,
      expandedKeys: [],
      treeKey: 0,
      editTitleInfo: {},
      i18nName: [],
      newParentId: '',
      editTitleType: 'new_menu', //rename_menu 重命名 new_menu 新建章节 new_sub_menu 新建子章节
    }
  }

  componentDidMount() {
    this.getMenuList()
  }

  componentWillReceiveProps(nextProps) {
    if (this.state.isSorting && !nextProps.isSorting) {
      this.cancelSort()
    }
  }

  //获取目录列表
  getMenuList = (needReload) => {
    this.setState({ loading: true });
    documentService.getDocumentMenu().then(res => {
      this.setState({ loading: false });
      if(res && res.data && res.data.length) {
        const selectedTreeNode = this.state.selectedTreeNode;
        this.setState({data: res.data, sourceData: deepFullCopy(res.data)});
        this.getExpandedKeys(res.data, selectedTreeNode);
        this.onTreeSelect([selectedTreeNode || res.data[0].id], this.props.selectedId ? true : needReload);
      }
      }).catch(() => {
      this.setState({ loading: false })
    })
  };

  //获取展开的目录
  getExpandedKeys = (data, key) => {
    let expandedKeys = this.state.expandedKeys;
    this.loopTree(data, key, item => {
      if (item.parentId && item.parentId !== '0') { //不是一级目录
        expandedKeys.push(item.parentId);
        this.setState({ expandedKeys }, () => {
          this.getExpandedKeys(data, item.parentId)
        })
      } else {
        expandedKeys.push(item.parentId);
        this.setState({ expandedKeys })
      }
    });
  };

  //新建／编辑 章节／子章节
  handleNewOrEdit = (key, id, parentId) => {
    this.setState({
      newTitleVisible: true,
      editTitleType: key,
      newParentId: key === 'new_menu' ? parentId : id
    })
  };

  //章节名称保存后
  afterTitleSave = (nodeInfo) => {
    this.setState({
      newTitleVisible: false,
      selectedTreeNode: nodeInfo.id
    }, () => {
      this.getMenuList(true)
    })
  };

  //排序
  handleSort = () => {
    this.setState({ isSorting: true });
    this.props.onSort(true)
  };

  /**
   * 遍历树，查找某个节点
   * @param data 树的数据结构
   * @param key  待查找节点的key
   * @param callback
   */
  loopTree = (data, key, callback) => {
    data.forEach((item, index, arr) => {
      if (item.id === key) {
        return callback(item, index, arr);
      }
      if (item.children && item.children.length) {
        return this.loopTree(item.children, key, callback);
      }
    })
  };

  onDrop = (info) => {
    const dragKey = info.dragNode.props.eventKey;
    const dropKey = info.node.props.eventKey;
    const dropPos = info.node.props.pos.split('-');
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
    const data = deepFullCopy(this.state.data);

    // Find dragObject
    let dragObj = {};
    this.loopTree(data, dragKey, (item, index, arr) => {
      arr.splice(index, 1);
      dragObj = item;
    });

    if (!info.dropToGap) { //拖拽到某个节点内
      this.loopTree(data, dropKey, item => {
        item.children = item.children || [];
        dragObj.parentId = item.id;
        item.children.push(dragObj);
      });
    } else if (
      (info.node.props.children || []).length > 0 //拖拽的节点有子节点
      && info.node.props.expanded // Is expanded
      && dropPosition === 1 // On the bottom gap
    ) {
      this.loopTree(data, dropKey, item => {
        item.children = item.children || [];
        dragObj.parentId = item.id;
        item.children.push(dragObj);
      });
    } else {
      let ar = [];
      let i = 0;
      this.loopTree(data, dropKey, (item, index, arr) => {
        dragObj.parentId = item.parentId;
        ar = arr;
        i = index;
      });
      if (dropPosition === -1) {
        ar.splice(i, 0, dragObj);
      } else {
        ar.splice(i + 1, 0, dragObj);
      }
    }
    this.setState({ data });
  };

  //保存排序
  handleSaveSort = () => {
    let dtos = [];
    let getDtos = (arr) => {
      arr.map(item => {
        dtos.push({
          id: item.id,
          parentId: item.parentId
        });
        item.children && getDtos(item.children)
      })
    };
    getDtos(this.state.data);
    this.setState({ loading: true });
    documentService.handleSort(dtos).then(res => {
      this.setState({
        loading: false,
        isSorting: false,
        sourceData: deepFullCopy(res.data)
      });
      this.props.onSort(false);
      message.success(messages('common.operate.success')/*操作成功*/);
    }).catch(() => {
      this.setState({ loading: false })
    })
  };

  //取消排序
  cancelSort = () => {
    this.setState({
      isSorting: false,
      data: deepFullCopy(this.state.sourceData)
    });
    this.props.onSort(false)
  };

  //操作树
  handleOperateMenu = (key, menuItem) => {
    switch(key) {
      case 'rename_menu':
        this.handleNewOrEdit(key, menuItem.id, menuItem.parentId);
        break;
      case 'new_menu':
      case 'new_sub_menu':
        this.handleNewOrEdit(key, menuItem.id, menuItem.parentId);
        break;
    }
  };

  //选择目录
  onTreeSelect = (key, needReload) => {
    const { treeKey, data} = this.state;
    let expandedKeys = this.state.expandedKeys;
    if (key && key.length) {
      let item = this.mapArrayFindId(data, key[0]);
      if(item.children && item.children.length){
        expandedKeys.addIfNotExist(key[0]);
      }
      this.setState({
        treeKey: treeKey + 1,
        expandedKeys,
      });
    }
    if (key[0] && (key[0] !== this.state.selectedTreeNode || needReload)) {
      // this.setState({ loading: true });
      documentService.getDocumentInfo(key[0]).then(res => {
        this.setState({
          selectedTreeNode: key[0],
          loading: false,
          i18nName: res.data.i18n.docTitle,
          editTitleInfo: res.data
        });
        this.props.onMenuSelect(res.data)
      }).catch(() => {
        this.setState({ loading: false })
      })
    }
  };


  //递归遍历查找menuList中的id为某值的元素
  mapArrayFindId = (arr, id) => {
    for(let i = 0; i < arr.length; i++){
      if(arr[i].id === id){
        return arr[i];
      }
      if(arr[i].children && arr[i].children.length){
        let res = this.mapArrayFindId(arr[i].children, id);
        if(res){
          return res;
        }
      }
    }
  };

  //渲染目录树
  renderTree = (data) => {
    const {isSorting} = this.state;
    return data.map(item => {
      const operateMenu = (
        <Menu onClick={e => this.handleOperateMenu(e.key, item)}>
          <Menu.Item key="rename_menu">{messages('basic-11.key119')/*重命名*/}</Menu.Item>
          <Menu.Item key="new_menu">{messages('basic-11.key147')/*新建章节*/}</Menu.Item>
          <Menu.Item key="new_sub_menu">{messages('basic-11.key148')/*新建子章节*/}</Menu.Item>
        </Menu>
      );
      if (item.children && item.children.length) {
        return (
          <TreeNode key={item.id} title={(
            <div className="menu-title">
              <Popover content={item.docTitle}>{item.docTitle}</Popover>
              {item.id === this.state.selectedTreeNode && !isSorting && (
                <Dropdown overlay={operateMenu}>
                  <Icon type="ellipsis" className="icon-more"/>
                </Dropdown>
              )}
            </div>
          )}>
            {this.renderTree(item.children)}
          </TreeNode>
        )
      } else {
        return (
          <TreeNode key={item.id} title={(
            <div className="menu-title">
              <Popover content={item.docTitle}>{item.docTitle}</Popover>
              {item.id === this.state.selectedTreeNode && !isSorting && (
                <Dropdown overlay={operateMenu}>
                  <Icon type="ellipsis" className="icon-more"/>
                </Dropdown>
              )}
            </div>
          )}/>
        )
      }
    })
  };

  render() {
    const { loading, newTitleVisible, isSorting, data, selectedTreeNode, editTitleInfo, i18nName, editTitleType,
      newParentId, expandedKeys, treeKey } = this.state;
    const newMenu = (
      <Menu onClick={e => this.handleNewOrEdit(e.key, selectedTreeNode, editTitleInfo.parentId)}>
        <Menu.Item key="new_menu">{messages('basic-11.key147')/*新建章节*/}</Menu.Item>
        <Menu.Item key="new_sub_menu">{messages('basic-11.key148')/*新建子章节*/}</Menu.Item>
      </Menu>
    );
    const {authPolicyAll} = this.props;
    return (
      <div className="help-document-menu">
        <Spin spinning={loading}>
          {isSorting ? (
            <Row className="menu-header sort-btn">
              <Button type="primary" onClick={this.handleSaveSort}>{messages('common.ok')/*确定*/}</Button>
              <Button onClick={this.cancelSort}>{messages('common.cancel')/*取消*/}</Button>
            </Row>
          ) : (
            authPolicyAll ?
              <Row className="menu-header">
              <Col span={12}>
                <Dropdown overlay={newMenu}>
                  <a><Icon type="plus" /> {messages('common.create')/*新建*/} <Icon type="caret-down" className="down-icon"/></a>
                </Dropdown>
              </Col>
              <Col span={12}>
                <a onClick={this.handleSort}><Icon type="swap" className="swap-icon"/>{messages('basic-11.key131')/*排序*/}</a>
              </Col>
            </Row>
              : null
          )}
          <div className={"tree-wrapper"}>
            <Tree className="draggable-tree"
                  draggable={isSorting}
                  selectedKeys={[selectedTreeNode]}
                  defaultExpandedKeys={expandedKeys}
                  onSelect={this.onTreeSelect}
                  onDrop={this.onDrop}
                  key={treeKey}
                  onExpand={expandedKeys => this.setState({expandedKeys})}
            >
              {this.renderTree(data)}
            </Tree>
          </div>
        </Spin>
        <NewDocumentTitle
          visible={newTitleVisible}
          info={editTitleType === 'rename_menu' ? editTitleInfo : {}}
          i18nName={editTitleType === 'rename_menu' ? i18nName : []}
          parentId={newParentId}
          onCancel={() => this.setState({newTitleVisible: false})}
          afterSave={this.afterTitleSave}
        />
      </div>
    )
  }
}

HelpDocumentMenu.propTypes = {
  isSorting: React.PropTypes.bool,
  selectedId: React.PropTypes.string,
  onSort: React.PropTypes.func,
  onMenuSelect: React.PropTypes.func, //选择目录
};

function mapStateToProps(state) {
  return {
    authPolicyAll: state.main.authPolicyAll,
  }
}

const WrappedHelpDocumentMenu = Form.create()(HelpDocumentMenu);
export default connect(mapStateToProps)(WrappedHelpDocumentMenu);
